<template>
	<view class="add-agent-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="back-icon" @tap="goBack">
				<up-icon name="arrow-left" size="20" color="#333"></up-icon>
			</view>
			<view class="title">创建 AI 智能体</view>
			<view class="right-action" @tap="autoComplete">
				<text class="action-text">一键完善</text>
			</view>
		</view>

		<!-- AI头像区域 -->
		<view class="avatar-section">
			<view class="avatar-container" @tap="chooseAvatar">
				<view class="avatar">
					<up-icon name="smiling-face" size="40" color="#6495ED" v-if="!formData.avatar"></up-icon>
					<image v-else :src="formData.avatar" mode="aspectFill" class="avatar-image"></image>
				</view>
				<view class="avatar-edit">
					<up-icon name="plus" size="16" color="#FFFFFF"></up-icon>
				</view>
			</view>
			<view class="avatar-text">AI 生成形象</view>
		</view>

		<!-- 表单区域 -->
		<view class="form-container">
			<up-form :model="formData" ref="uForm" :rules="rules" :errorType="errorType">
				<!-- 名称输入 -->
				<up-form-item label="名称" prop="name" borderBottom>
					<up-input v-model="formData.name" placeholder="输入名称" border="none"></up-input>
				</up-form-item>

				<!-- 描述输入 -->
				<up-form-item label="设定描述" prop="description" borderBottom>
					<up-textarea v-model="formData.description"
						placeholder="示例：你是一位经验丰富的英语老师，拥有激发学生学习热情的教学方法，你善于运用幽默和实际应用案例，使对话充满趣味。" height="120" count
						maxlength="300"></up-textarea>
					<view class="clear-btn" @tap="clearDescription" v-if="formData.description">
						<up-icon name="close-circle" color="#CCCCCC" size="18"></up-icon>
					</view>
				</up-form-item>

				<!-- 基础设置 -->
				<up-form-item label="声音" prop="voice" borderBottom @tap="selectVoice">
					<view class="voice-selector">
						<text>{{ formData.voice }}</text>
						<up-icon name="arrow-right" size="16" color="#CCCCCC"></up-icon>
					</view>
				</up-form-item>

				<up-form-item label="语言" prop="language" borderBottom @tap="selectLanguage">
					<view class="language-selector">
						<text>{{ formData.language }}</text>
						<up-icon name="arrow-right" size="16" color="#CCCCCC"></up-icon>
					</view>
				</up-form-item>

				<up-form-item label="公开设置" prop="visibility" borderBottom @tap="selectVisibility">
					<view class="visibility-selector">
						<text>{{ formData.visibility }}</text>
						<up-icon name="arrow-right" size="16" color="#CCCCCC"></up-icon>
					</view>
				</up-form-item>

				<!-- 高级设置折叠区域 -->
				<!-- <view class="advanced-settings">
					<view class="advanced-header" @tap="toggleAdvanced">
						<up-icon :name="showAdvanced ? 'minus' : 'plus'" size="16" color="#3c9cff"></up-icon>
						<text class="advanced-text">更多高级设置</text>
					</view>

					<view class="advanced-content" v-if="showAdvanced">
						<up-form-item label="知识库" prop="knowledgeBase" borderBottom>
							<up-switch v-model="formData.knowledgeBase" activeColor="#3c9cff"></up-switch>
						</up-form-item>

						<up-form-item label="记忆能力" prop="memory" borderBottom>
							<up-switch v-model="formData.memory" activeColor="#3c9cff"></up-switch>
						</up-form-item>

						<up-form-item label="模型选择" prop="model" borderBottom @tap="selectModel">
							<view class="model-selector">
								<view class="selector-item">
									<text class="selector-icon">🤖</text>
									<text class="selector-text">{{ formData.model }}</text>
								</view>
								<up-icon name="arrow-right" size="16" color="#CCCCCC"></up-icon>
							</view>
						</up-form-item>
						
						<up-form-item label="温度" prop="temperature" borderBottom>
							<view class="temperature-slider">
								<text class="slider-value">{{ formData.temperature }}</text>
								<up-slider
									v-model="formData.temperature"
									:min="0"
									:max="1"
									:step="0.1"
									activeColor="#3c9cff"
								></up-slider>
							</view>
						</up-form-item>
						
						<up-form-item label="最大回复长度" prop="maxLength" borderBottom>
							<up-number-box v-model="formData.maxLength" :min="100" :max="4000" :step="100"></up-number-box>
						</up-form-item>
					</view>
				</view> -->
			</up-form>
		</view>

		<!-- 底部创建按钮 -->
		<view class="footer">
			<up-button type="primary" text="创建智能体" @tap="submitForm" :loading="loading"></up-button>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useChatMenu } from '@/stores/chatMenu.js';

// 表单数据
const formData = reactive({
	name: '',
	description: '',
	avatar: '',
	voice: '默认',
	language: '中文',
	visibility: '公开 - 所有人可对话',
	knowledgeBase: false,
	memory: true,
	model: '',
	temperature: 0.7,
	maxLength: 2000
});

// 表单校验规则
const rules = {
	name: [{
		required: true,
		message: '请输入智能体名称',
		trigger: ['blur', 'change']
	}],
	description: [{
		required: true,
		message: '请输入设定描述',
		trigger: ['blur', 'change']
	}]
};

// 表单引用
const uForm = ref(null);
// 错误提示类型
const errorType = ref('message');
// 是否显示高级设置
const showAdvanced = ref(false);
// 加载状态
const loading = ref(false);

// 返回上一页
const goBack = () => {
	uni.navigateBack();
};

// 清除描述内容
const clearDescription = () => {
	formData.description = '';
};

// 切换高级设置显示状态
const toggleAdvanced = () => {
	showAdvanced.value = !showAdvanced.value;
};

// 选择头像
const chooseAvatar = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			// 将临时文件保存到本地永久存储
			console.log('选择图片成功：', res)
			uni.saveFile({
				tempFilePath: res.tempFilePaths[0],
				success: function(saveRes) {
					// 使用永久路径
					console.log('保存文件成功：', saveRes);
					formData.avatar = saveRes.savedFilePath;
				},
				fail: function(err) {
					console.error('保存文件失败：', err);
					uni.showToast({
						title: '保存头像失败',
						icon: 'none'
					});
				}
			});
		}
	});
};

// 选择声音
const selectVoice = () => {
	uni.showActionSheet({
		itemList: ['默认', '男声', '女声', '童声'],
		success: (res) => {
			const voices = ['默认', '男声', '女声', '童声'];
			formData.voice = voices[res.tapIndex];
		}
	});
};

// 选择语言
const selectLanguage = () => {
	uni.showActionSheet({
		itemList: ['中文', '英文', '日文', '韩文', '法文', '德文'],
		success: (res) => {
			const languages = ['中文', '英文', '日文', '韩文', '法文', '德文'];
			formData.language = languages[res.tapIndex];
		}
	});
};

// 选择可见性
const selectVisibility = () => {
	uni.showActionSheet({
		itemList: ['公开 - 所有人可对话', '私有 - 仅自己可见'],
		success: (res) => {
			const visibilities = ['公开 - 所有人可对话', '私有 - 仅自己可见'];
			formData.visibility = visibilities[res.tapIndex];
		}
	});
};

// 选择模型
const selectModel = () => {
	uni.showActionSheet({
		itemList: ['GPT-3.5', 'GPT-4', 'Claude', 'Gemini'],
		success: (res) => {
			const models = ['GPT-3.5', 'GPT-4', 'Claude', 'Gemini'];
			formData.model = models[res.tapIndex];
		}
	});
};

// 一键完善内容
const autoComplete = () => {
	formData.name = '英语老师';
	formData.description = '你是一位经验丰富的英语老师，拥有激发学生学习热情的教学方法，你善于运用幽默和实际应用案例，使对话充满趣味。你可以帮助学生提高口语、听力、阅读和写作能力，并提供个性化的学习建议。';

	uni.showToast({
		title: '已完善内容',
		icon: 'success'
	});
};

// 提交表单
const submitForm = () => {
	console.log(formData, "formData");
	uForm.value.validate().then(valid => {
		// console.log(valid, "??!");
		if (valid) {
			loading.value = true;
			// 模拟提交

			loading.value = false;

			// 创建成功后添加到聊天列表并跳转到聊天详情页
			const chatStore = useChatMenu();

			// 生成唯一ID
			const newId = Date.now();
			console.log(newId, 'newId')
			// 创建新的聊天对象
			const newChat = {
				id: newId,
				name: formData.name,
				avatar: formData.avatar || '/static/img/chat/testUserA.jpg', // 使用选择的头像或默认头像
				description: formData.description,
				voice: formData.voice,
				language: formData.language,
				visibility: (formData.visibility === "公开 - 所有人可对话")?"public":"private",
				knowledgeBase: formData.knowledgeBase,
				memory: formData.memory,
				model: formData.model,
				temperature: formData.temperature,
				maxLength: formData.maxLength,
				lastMessage: '开始新的对话...',
				time: new Date().toLocaleTimeString(),
				unread: 0,
				isPinned: false,
				isMuted: false,
				x: 0
			};

			// 将新聊天添加到列表开头
			chatStore.chatMenu.unshift(newChat);
			// 同步更新到Pinia store
			chatStore.changeChatMenu(chatStore.chatMenu);

			uni.showToast({
				title: '创建成功',
				icon: 'success'
			});

			// 导航到聊天详情页
			uni.redirectTo({
				url: `/pages/chatDetail/chatDetail?id=${newChat.id}&name=${encodeURIComponent(newChat.name)}&avatar=${encodeURIComponent(newChat.avatar)}&description=${encodeURIComponent(formData.description)}&voice=${encodeURIComponent(formData.voice)}&language=${encodeURIComponent(formData.language)}&model=${encodeURIComponent(formData.model)}&isNew=true`
			});
		} else {
			uni.showToast({
				title: '请完善表单信息',
				icon: 'none'
			});
		}
	});
};
</script>
<style lang="scss" scoped>
.add-agent-container {
	padding: 0 20rpx;
	background-color: #f8f8f8;
	min-height: 100vh;
}

.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 90rpx;
	position: relative;
}

.back-icon {
	padding: 10rpx;
}

.title {
	font-size: 36rpx;
	font-weight: 500;
	position: absolute;
	left: 50%;
	transform: translateX(-50%);
}

.right-action {
	padding: 10rpx;
}

.action-text {
	color: #3c9cff;
	font-size: 28rpx;
}

.avatar-section {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin: 40rpx 0;
}

.avatar-container {
	position: relative;
	width: 160rpx;
	height: 160rpx;
}

.avatar {
	width: 160rpx;
	height: 160rpx;
	border-radius: 50%;
	background-color: #e6f2ff;
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: hidden;
}

.avatar-image {
	width: 100%;
	height: 100%;
	border-radius: 50%;
}

.avatar-edit {
	position: absolute;
	right: 0;
	bottom: 0;
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background-color: #3c9cff;
	display: flex;
	justify-content: center;
	align-items: center;
}

.avatar-text {
	margin-top: 20rpx;
	font-size: 28rpx;
	color: #666;
}

.form-container {
	background-color: #fff;
	border-radius: 16rpx;
	padding: 20rpx;
	margin-bottom: 40rpx;
}

.clear-btn {
	position: absolute;
	right: 20rpx;
	top: 20rpx;
}

.voice-selector,
.language-selector,
.visibility-selector,
.model-selector {
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	height: 60rpx;

	.selector-left {
		display: flex;
		align-items: center;

		.selector-icon {
			margin-right: 10rpx;
		}

		text {
			font-size: 28rpx;
			color: #333;
		}
	}
}

.advanced-settings {
	margin-top: 30rpx;
}

.advanced-header {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
}

.advanced-text {
	margin-left: 10rpx;
	color: #3c9cff;
	font-size: 28rpx;
}

.advanced-content {
	margin-top: 20rpx;
}

.temperature-slider {
	display: flex;
	align-items: center;
	width: 100%;
}

.slider-value {
	margin-right: 20rpx;
	min-width: 40rpx;
	text-align: center;
}

.footer {
	padding: 40rpx 20rpx;
}
</style>
